package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public UserLoginVO getUserById(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO =new UserLoginVO();
        String openId = getOpenId(userLoginDTO.getCode());
        log.info("openId:{}",openId);
        if (openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectById(openId);
        if (user == null){
            user =User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.insertUser(user);
        }
        Map<String,Object> map =new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        userLoginVO.setId(user.getId());
        userLoginVO.setToken(jwt);
        userLoginVO.setOpenid(openId);
        return userLoginVO;
    }

    private String getOpenId(String code) {
        Map paramData = new HashMap();
        paramData.put("appid",weChatProperties.getAppid());
        paramData.put("secret",weChatProperties.getSecret());
        paramData.put("js_code",code);
        paramData.put("grant_type","authorization_code");
        log.info("paramData:{}",paramData);
        String content = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramData);
        log.info("content:{}",content);
        JSONObject jsonObject = JSON.parseObject(content);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
